package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.ProcessEntityDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.AlertDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-05
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param dto 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertDataVo> selectAlertDataList(AlertDataDto dto) {
        LambdaQueryWrapper<AlertData> wrapper = new LambdaQueryWrapper<AlertData>()
                .eq(dto.getDeviceName() != null, AlertData::getDeviceName, dto.getDeviceName())
                .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                .between(dto.getStartTime() != null || dto.getEndTime() != null, AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime());
        List<AlertData> list = list(wrapper);

        List<AlertDataVo> vos = BeanUtil.copyToList(list, AlertDataVo.class);

        vos.forEach(vo -> {
            Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, vo.getIotId()));
            vo.setNickname(device.getDeviceName());
            vo.setDeviceName(device.getNodeId());
        });
        return vos;

    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 2.1.2 处理设备报警数据
     *
     * @param dto 传入封装数据
     * @return
     */
    @Override
    public int handleProcessAlertData(ProcessEntityDto dto) {
        // 1. 参数校验
        Long id = dto.getId();
        if (id == null) {
            throw new IllegalArgumentException("报警数据ID不能为空");
        }
        String processingResult = dto.getProcessingResult();
        if (BeanUtil.isEmpty(processingResult)) {
            throw new IllegalArgumentException("处理结果不能为空");
        }

        // 2. 仅通过ID查询数据
        AlertData alertData = alertDataMapper.selectOne(
                Wrappers.<AlertData>lambdaQuery()
                        .eq(AlertData::getId, id)
        );

        // 3. 数据存在性校验
        if (BeanUtil.isEmpty(alertData)) {
            // 抛出更具体的业务异常，包含关键参数便于排查
            throw new BaseException("未找到ID为[" + id + "]的报警数据");
        }

        // 4. 时间处理优化（
        String processingTimeStr = dto.getProcessingTime();
        LocalDateTime processingTime;
        if (BeanUtil.isEmpty(processingTimeStr)) {
            // 若未传递时间，默认使用当前时间
            processingTime = LocalDateTime.now();
        } else {
            try {
                processingTime = LocalDateTimeUtil.parse(processingTimeStr, DatePattern.UTC_MS_PATTERN);
                processingTime = DateTimeZoneConverter.utcToShanghai(processingTime);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException("时间格式转换失败，正确格式应为：" );
            }
        }

        // 5. 设置更新字段
        alertData.setProcessingResult(processingResult);  // 用新值更新
        alertData.setProcessingTime(processingTime);
        alertData.setStatus(1);  // 标记为已处理

        // 6. 执行更新
        return updateAlertData(alertData);
    }
}
